Popular Searches
Popular Course Categories
Popular Courses

Dynamic XPath

Advanced Selenium

Dynamic XPath in Selenium

Dynamic XPath is an advanced XPath technique used in Selenium WebDriver to locate web elements whose attributes, values, positions, or surrounding HTML structure change dynamically at runtime. Dynamic XPath helps automation testers create flexible and reliable locators for modern web applications where static attributes such as IDs, class names, or text values may change frequently.

In real-world Selenium automation, dynamic elements are common in applications built with JavaScript frameworks such as React, Angular, Vue, and other dynamic web technologies. Dynamic XPath techniques allow testers to locate such elements by using stable attributes, partial matches, relationships between elements, and XPath functions.

Dynamic XPath is especially useful for login forms, search results, e-commerce product lists, tables, menus, buttons, dynamic IDs, changing class names, and elements whose position changes depending on application data.

Course Resource: Selenium Training | Register for Course Demo


1. What is XPath?

XPath stands for XML Path Language. In Selenium, XPath is commonly used to identify elements in an HTML DOM when other locators such as ID, name, class name, or CSS selector are not suitable or sufficiently stable.

XPath allows Selenium to navigate through the HTML structure and identify elements using attributes, text, hierarchy, relationships, and functions.

driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");

Here, Selenium searches for an input element whose id attribute is username.


2. What is Dynamic XPath?

Dynamic XPath is an XPath expression designed to locate elements even when some properties of the element change dynamically.

For example, suppose a web application generates the following IDs:

username_12345

username_67891

username_54321

A static XPath such as:

//input[@id='username_12345']

may fail when the application generates a different ID. A dynamic XPath can identify the stable part of the ID:

//input[contains(@id,'username_')]

This XPath can match elements whose ID starts with or contains the stable portion username_.


3. Why is Dynamic XPath Important?

Dynamic XPath is important because modern web applications frequently generate dynamic attributes. A locator that depends on an unstable value can cause automation scripts to fail.

  • Handles dynamically generated IDs.
  • Handles changing class names.
  • Locates elements using partial attribute values.
  • Supports dynamic text matching.
  • Allows navigation through parent-child relationships.
  • Supports locating elements using sibling relationships.
  • Helps automate dynamic tables and lists.
  • Improves locator flexibility.
  • Can reduce dependence on unstable attributes.
  • Is useful for complex Selenium automation frameworks.


4. Static XPath vs Dynamic XPath

Static XPathDynamic XPath
Uses exact values.Can use partial or flexible values.
More dependent on fixed attributes.Can work with changing attributes.
Simple to create.Requires more XPath knowledge.
May fail when values change.Can remain valid when dynamic values change.
Suitable for stable elements.Suitable for dynamic elements.


5. Basic XPath Syntax

The basic XPath syntax is:

//tagname[@attribute='value']

Example:

//input[@id='username']

Another example:

//button[@type='submit']

Dynamic XPath techniques extend this basic syntax using functions and relationships.


6. Absolute XPath vs Relative XPath

Absolute XPath

Absolute XPath starts from the root of the HTML document and follows the complete hierarchy.

/html/body/div/div/form/input

Absolute XPath is generally fragile because any change in the HTML hierarchy can break the locator.

Relative XPath

Relative XPath starts from a specific location in the DOM and generally begins with //.

//input[@id='username']

Relative XPath is usually more practical for Selenium automation because it can focus on meaningful attributes and relationships rather than the complete DOM hierarchy.


7. XPath with contains()

The contains() function is one of the most commonly used techniques for creating dynamic XPath expressions.

Syntax:

//tag[contains(@attribute,'partialValue')]

Example:

//input[contains(@id,'username')]

If the actual ID changes from:

username_123

username_456

username_789

the XPath can still locate the element because it searches for the stable portion username.


8. contains() with Class Attribute

Dynamic class names are common in modern web applications.

//button[contains(@class,'login')]

This can match a button such as:

<button class="btn login primary">Login</button>

Another example:

//div[contains(@class,'product-card')]


9. contains() with Text

The contains() function can also be combined with text().

//button[contains(text(),'Login')]

This can be useful when the complete button text is dynamic but contains a stable word.

For example:

<button>Login Now</button>

XPath:

//button[contains(text(),'Login')]


10. XPath text() Function

The text() function is used to locate elements based on their visible text.

//button[text()='Login']

This XPath looks for a button whose text exactly matches Login.

For dynamic text, combine text() with contains():

//button[contains(text(),'Log')]


11. normalize-space()

The normalize-space() function is useful when text contains extra spaces or inconsistent whitespace.

//button[normalize-space()='Login']

For example, it can help locate an element when the HTML contains unexpected whitespace around the visible text.

//button[normalize-space()='Submit']

This is often more reliable than an exact text comparison when whitespace formatting is inconsistent.


12. starts-with() Function

The starts-with() function identifies elements where an attribute begins with a specific value.

Syntax:

//tag[starts-with(@attribute,'value')]

Example:

//input[starts-with(@id,'user_')]

If the application generates:

user_123

user_456

user_789

the XPath can locate the elements using their common prefix.


13. contains() vs starts-with()

FunctionPurposeExample
contains()Matches a value appearing anywhere inside an attribute.contains(@id,'user')
starts-with()Matches a value at the beginning of an attribute.starts-with(@id,'user_')


14. Dynamic XPath with Multiple Attributes

Multiple attributes can be combined using the and operator.

//input[@type='text' and @name='username']

This approach is useful when one attribute is not unique.

Example:

//input[contains(@class,'form-control') and @type='text']


15. Dynamic XPath with OR

The or operator can be used when an element can be identified using either of two conditions.

//input[@id='username' or @name='username']

This can be useful when the same application may render slightly different markup in different situations.


16. Dynamic XPath Using Parent

XPath can navigate from a child element to its parent using .. or the parent:: axis.

//input[@id='username']/parent::div

This technique is useful when the child has a stable attribute but the desired clickable or container element is the parent.


17. Dynamic XPath Using Child

The child:: axis can be used to navigate from a parent to its child elements.

//div[@id='loginForm']/child::input

A shorter equivalent can often be:

//div[@id='loginForm']//input


18. Dynamic XPath Using Descendant

The descendant relationship is useful when the target element can appear at different levels below a known parent.

//div[@id='loginForm']//input[@name='username']

The double slash after the parent allows Selenium to search through descendant elements.


19. Dynamic XPath Using Ancestor

The ancestor axis can locate a parent or higher-level container of an element.

//input[@name='username']/ancestor::form

This can be useful when a child element is easy to identify but the required container is higher in the DOM hierarchy.


20. Dynamic XPath Using Following-Sibling

The following-sibling axis locates elements that appear after the current element at the same hierarchical level.

//label[text()='Username']/following-sibling::input

This technique is useful when a label has stable text but the input does not have a reliable unique attribute.


21. Dynamic XPath Using Preceding-Sibling

The preceding-sibling axis locates an element that appears before the current element.

//input[@name='username']/preceding-sibling::label

This can be useful for relationships between labels, fields, icons, and other controls.


22. Dynamic XPath Using Following

The following axis can locate elements appearing later in the document relative to the current node.

//label[text()='Username']/following::input[1]

The positional index [1] can be used when the first matching element is required.


23. Dynamic XPath Using Preceding

The preceding axis can locate elements appearing before the current element in the document.

//button[text()='Submit']/preceding::input[1]


24. Dynamic XPath with Index

XPath indexes can be used when multiple elements match the same expression.

(//input[@type='text'])[1]

Another example:

(//button[contains(@class,'btn')])[2]

Indexes should be used carefully because DOM order can change when the application is modified.


25. Dynamic XPath with Position

The position() function can identify an element based on its position within a node set.

//table//tr[position()=2]

This identifies the second matching table row.


26. Dynamic XPath with last()

The last() function can locate the last matching element.

//table//tr[last()]

This is useful when the last row or last matching item is required.


27. Dynamic XPath for Tables

Dynamic XPath is particularly useful for automating HTML tables where the row and column positions change according to application data.

Example table:

<table>

    <tr>

        <th>Product</th>

        <th>Price</th>

    </tr>

    <tr>

        <td>Laptop</td>

        <td>$1000</td>

    </tr>

</table>

XPath for the Laptop row:

//table//tr[td[text()='Laptop']]

XPath for the price associated with Laptop:

//table//tr[td[text()='Laptop']]/td[2]


28. Dynamic XPath for E-Commerce Products

E-commerce applications frequently display products using repeated cards. Dynamic XPath can locate a specific product based on its name.

//div[contains(@class,'product-card')][.//h2[text()='Laptop']]

To locate the product's button:

//div[contains(@class,'product-card')][.//h2[text()='Laptop']]//button

This approach avoids depending on the product's changing position in the page.


29. Dynamic XPath for Product Price

If the product name is stable but the price changes, the product can be located first and its price can then be selected relative to it.

//div[contains(@class,'product-card')][.//h2[text()='Laptop']]//*[contains(@class,'price')]


30. Dynamic XPath for Login Page

Consider a login form:

<input type="text" id="user_12345">

<input type="password" id="pass_67890">

<button id="login_98765">Login</button>

Dynamic XPath expressions can be:

//input[starts-with(@id,'user_')]

//input[starts-with(@id,'pass_')]

//button[contains(@id,'login_')]


31. Dynamic XPath for Buttons

Buttons may contain changing classes or generated IDs. A stable text or partial attribute can be used.

//button[contains(text(),'Submit')]

Or:

//button[contains(@class,'submit')]

Or using multiple conditions:

//button[contains(@class,'btn') and contains(text(),'Submit')]


32. Dynamic XPath for Links

Links can also contain dynamic URLs or changing text.

//a[contains(text(),'Profile')]

For dynamic href values:

//a[contains(@href,'profile')]

If the URL begins with a stable prefix:

//a[starts-with(@href,'/profile')]


33. Dynamic XPath for Checkboxes

Checkboxes can be located using stable surrounding text or attributes.

//label[contains(text(),'Accept Terms')]/input

Another example:

//input[@type='checkbox' and contains(@name,'terms')]


34. Dynamic XPath for Radio Buttons

//input[@type='radio' and @value='male']

For partial values:

//input[@type='radio' and contains(@value,'male')]


35. Dynamic XPath for Dropdown Options

Dynamic XPath can be used to locate a specific option based on its visible text.

//select[@id='country']/option[text()='India']

For partial text:

//select[@id='country']/option[contains(text(),'Ind')]


36. Dynamic XPath for Search Results

Search result pages often contain repeated elements. A dynamic XPath can locate a result using its title.

//div[contains(@class,'search-result')][.//h3[contains(text(),'Selenium')]]

This is more flexible than selecting a result by its fixed position.


37. Dynamic XPath for Menus

Navigation menus can be located using visible text.

//nav//a[contains(text(),'Products')]

If the menu contains dynamic classes:

//nav//*[contains(@class,'menu-item')]//a[contains(text(),'Products')]


38. Dynamic XPath with Multiple Conditions

Multiple conditions can make a dynamic XPath more specific.

//input[

    @type='text'

    and contains(@class,'form-control')

    and starts-with(@id,'user_')

]

In a compact Selenium expression:

driver.findElement(By.xpath("//input[@type='text' and contains(@class,'form-control') and starts-with(@id,'user_')]"));


39. Dynamic XPath with not()

The not() function can exclude unwanted elements.

//input[@type='text' and not(@disabled)]

This expression can help identify text inputs that are not disabled.


40. Dynamic XPath Using @ Attribute

The @ symbol is used to reference an HTML attribute.

//input[@name='username']

//button[@type='submit']

//a[@href='/login']

Attributes commonly used in dynamic XPath include:

  • id
  • name
  • class
  • type
  • value
  • href
  • title
  • placeholder
  • aria-label
  • data-* attributes


41. Dynamic XPath Using Custom Attributes

Modern applications often provide custom attributes such as data-testid, data-id, or data-test.

//button[@data-testid='login-button']

When these attributes are intentionally designed for testing and remain stable, they can provide reliable locators.


42. Dynamic XPath Using aria-label

Accessibility attributes such as aria-label can sometimes provide stable element identification.

//button[@aria-label='Search']

For partial values:

//button[contains(@aria-label,'Search')]


43. Dynamic XPath with normalize-space() and contains()

Both functions can be combined when visible text contains inconsistent whitespace and additional text.

//button[contains(normalize-space(),'Submit')]

This can be useful when the displayed text contains additional spaces or formatting.


44. Dynamic XPath for Nested Elements

Nested elements can be located by first identifying a stable parent and then searching inside it.

//div[@id='loginForm']//input[contains(@name,'user')]

This strategy is useful when multiple elements on the page have similar attributes.


45. Dynamic XPath Using Parent-Child Relationship

Consider:

<div class="form-group">

    <label>Username</label>

    <input type="text">

</div>

The input can be located relative to the label:

//label[text()='Username']/following-sibling::input


46. Dynamic XPath Using Sibling Relationship

Sibling-based XPath is useful when one element has stable text and the target element is next to it.

//span[text()='Email']/following-sibling::input

Another example:

//input[@name='email']/preceding-sibling::label


47. Dynamic XPath for Repeated Elements

When many elements have the same structure, a parent-child relationship can distinguish the required element.

//div[contains(@class,'user-card')][.//span[text()='John']]//button[contains(text(),'Edit')]

This expression first identifies John's card and then finds the Edit button inside that card.


48. Dynamic XPath for Dynamic IDs

Dynamic IDs are one of the most common reasons for using dynamic XPath.

Suppose the application generates:

input_1001

input_1002

input_1003

Instead of:

//input[@id='input_1001']

Use:

//input[starts-with(@id,'input_')]


49. Dynamic XPath for Changing Class Names

Suppose an application generates:

btn_primary_123

btn_primary_456

btn_primary_789

A partial class match can be used:

//button[contains(@class,'btn_primary')]

When classes contain multiple tokens, testers should ensure that the selected partial value is sufficiently specific.


50. Dynamic XPath for Changing Text

If an element's text contains a stable word but additional text changes, use contains().

//div[contains(text(),'Welcome')]

For example:

Welcome John

Welcome David

Welcome Robert

All may be matched using:

//div[contains(text(),'Welcome')]


51. Dynamic XPath with Selenium WebDriver

Once a dynamic XPath is created, it can be passed to Selenium's By.xpath() locator.

WebElement username = driver.findElement(

    By.xpath("//input[starts-with(@id,'user_')]")

);

 

username.sendKeys("admin");

Another example:

driver.findElement(

    By.xpath("//button[contains(text(),'Login')]")

).click();


52. Dynamic XPath with Explicit Wait

Creating a correct XPath is only one part of reliable automation. Dynamic applications may also require synchronization.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//button[contains(text(),'Login')]")

    )

);

 

loginButton.click();

A stable dynamic XPath combined with an appropriate explicit wait can make Selenium automation more reliable.


53. Dynamic XPath for AJAX Elements

AJAX-based applications may add or update elements without a complete page refresh. Their attributes or positions may change dynamically.

For such elements, use:

  • Stable attributes.
  • Partial attribute matching.
  • Text-based identification.
  • Parent-child relationships.
  • Explicit waits.
  • Meaningful application-specific attributes.


54. Dynamic XPath for React Applications

React applications may generate dynamic classes, IDs, and nested DOM structures. Instead of relying on generated values, look for stable attributes such as testing attributes, accessibility attributes, meaningful text, or predictable relationships.

//button[@data-testid='login-button']

Or:

//button[contains(@aria-label,'Login')]

The exact locator should depend on the application's DOM and the stability of the selected attribute.


55. Dynamic XPath for Angular Applications

Angular applications can also contain dynamically generated attributes and repeated components.

A stable custom attribute can be preferable:

//button[@data-test='submit']

When no stable attribute is available, relationship-based XPath can be used.

//label[normalize-space()='Username']/following-sibling::input


56. Dynamic XPath for Vue Applications

Vue applications can also update DOM elements dynamically. The same general XPath principles apply: identify stable attributes, meaningful text, and reliable relationships.

//button[contains(@class,'login-button')]


57. Dynamic XPath for Pagination

Pagination controls often contain changing page numbers.

//a[normalize-space()='3']

For a dynamic page number supplied by Java:

String pageNumber = "3";

 

driver.findElement(

    By.xpath("//a[normalize-space()='" + pageNumber + "']")

).click();


58. Dynamic XPath for Dynamic Table Rows

Suppose a table contains users and their statuses. To locate the row for a specific user:

//table//tr[td[normalize-space()='John']]

To click an action button inside that row:

//table//tr[td[normalize-space()='John']]//button[contains(text(),'Edit')]

This is a powerful technique for handling data-driven tables.


59. Dynamic XPath with Java Variables

XPath expressions can be dynamically constructed using Java variables.

String productName = "Laptop";

 

String xpath = "//div[contains(@class,'product-card')][.//h2[normalize-space()='" 

        + productName + "']]";

 

driver.findElement(By.xpath(xpath)).click();

This allows the same automation logic to work with different data.


60. Dynamic XPath for Data-Driven Testing

Dynamic XPath works well with TestNG Data Providers. Test data can be used to construct XPath expressions dynamically.

@DataProvider(name = "products")

public Object[][] products() {

    return new Object[][] {

        {"Laptop"},

        {"Mobile"},

        {"Headphones"}

    };

}

 

@Test(dataProvider = "products")

public void productTest(String product) {

 

    String xpath =

        "//div[contains(@class,'product-card')][.//h2[normalize-space()='"

        + product + "']]";

 

    driver.findElement(By.xpath(xpath)).click();

}


61. Dynamic XPath and Page Object Model

Dynamic XPath should generally be maintained inside Page Object classes rather than scattered throughout test methods. This keeps locator logic centralized and makes framework maintenance easier.

public class ProductPage {

 

    private WebDriver driver;

 

    public ProductPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void selectProduct(String productName) {

 

        String xpath =

            "//div[contains(@class,'product-card')][.//h2[normalize-space()='"

            + productName + "']]";

 

        driver.findElement(By.xpath(xpath)).click();

    }

}


62. Dynamic XPath Utility Method

A reusable utility method can generate dynamic XPath locators.

public By productLocator(String productName) {

 

    String xpath =

        "//div[contains(@class,'product-card')][.//h2[normalize-space()='"

        + productName + "']]";

 

    return By.xpath(xpath);

}

The test can then use:

driver.findElement(

    productPage.productLocator("Laptop")

).click();


63. Handling Quotes in Dynamic XPath

Special care is required when dynamic values contain quotes because XPath strings use single or double quotation marks.

For example:

String text = "Men's Shoes";

A simple XPath concatenation may require special handling when the data itself contains an apostrophe.

In a mature automation framework, XPath construction utilities can be used to safely create XPath string expressions for arbitrary text.


64. XPath concat() Function

The concat() function can combine multiple strings in XPath.

concat('Men', "'", 's Shoes')

This can be useful when a target text contains both single and double quote characters and a normal XPath string literal is insufficient.


65. Dynamic XPath with Class Tokens

HTML class attributes can contain multiple class names:

<button class="btn btn-primary login-button">Login</button>

A common approach is:

//button[contains(@class,'login-button')]

For strict class-token matching, a normalized class expression can be used:

//button[contains(concat(' ', normalize-space(@class), ' '), ' login-button ')]

This reduces the risk of accidentally matching a class whose name merely contains the same characters.


66. Dynamic XPath for Unique Elements

A good dynamic XPath should ideally identify one intended element. Before using a locator in Selenium, validate that it uniquely identifies the desired element in the current DOM.

//input[@name='username']

If this matches multiple elements, add another stable condition:

//form[@id='loginForm']//input[@name='username']


67. XPath Validation in Browser Developer Tools

Chrome and other modern browsers provide developer tools that can be used to inspect the DOM and test XPath expressions.

In Chrome DevTools, an XPath can commonly be tested from the Console using:

$x("//button[contains(text(),'Login')]")

This helps determine whether an XPath matches the intended element before adding it to Selenium code.


68. Dynamic XPath Debugging Process

When a dynamic XPath fails, use a systematic debugging process:

  1. Inspect the current HTML.
  2. Check whether the element exists.
  3. Verify the XPath syntax.
  4. Test the XPath in browser developer tools.
  5. Check whether multiple elements are matched.
  6. Check whether the element is inside an iframe.
  7. Check whether the element is dynamically rendered.
  8. Check whether an explicit wait is required.
  9. Check whether the DOM changes after the page loads.
  10. Update the locator using stable attributes or relationships.


69. Common Mistakes in Dynamic XPath

  • Using complete dynamic IDs.
  • Depending on unstable generated class names.
  • Using overly long absolute XPath expressions.
  • Using indexes when a stable attribute exists.
  • Using text that changes frequently.
  • Creating XPath expressions that match multiple elements.
  • Ignoring whitespace differences.
  • Ignoring iframe boundaries.
  • Using XPath to solve a synchronization problem.
  • Using complex XPath when a simpler stable locator is available.
  • Hard-coding dynamic values that should come from test data.


70. Best Practices for Dynamic XPath

  • Prefer stable attributes whenever possible.
  • Use meaningful application-specific attributes such as data-testid when available.
  • Use contains() for stable portions of changing attributes.
  • Use starts-with() when an attribute has a predictable prefix.
  • Use text carefully when visible text is stable.
  • Use parent-child relationships when direct attributes are unavailable.
  • Use sibling relationships for label-field structures.
  • Avoid unnecessary XPath complexity.
  • Validate uniqueness before using a locator.
  • Use explicit waits for dynamically rendered elements.
  • Keep locators inside Page Object classes.
  • Use reusable methods for frequently generated dynamic XPath expressions.
  • Avoid relying on fragile indexes.
  • Keep test data separate from locator logic.


71. Dynamic XPath vs CSS Selector

FeatureDynamic XPathCSS Selector
Partial attribute matchingYesYes
Text-based locationYesNot directly
Parent traversalYesMore limited depending on selector capabilities
Sibling navigationYesYes for many cases
Complex DOM relationshipsStrongGood but different syntax
Learning complexityHigherOften simpler for straightforward selectors

Neither XPath nor CSS is universally preferable. The locator should be selected based on stability, readability, uniqueness, and the application's DOM.


72. Dynamic XPath vs ID Locator

ID LocatorDynamic XPath
Very simple when ID is stable.Useful when IDs change dynamically.
Usually concise.Can express complex relationships.
Fast and readable.Flexible for dynamic structures.
Depends on stable ID.Can use stable portions of attributes or DOM relationships.


73. Practical Login Automation Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class DynamicXPathLoginTest {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        String usernameXPath =

            "//input[starts-with(@id,'username_')]";

 

        String passwordXPath =

            "//input[starts-with(@id,'password_')]";

 

        String loginButtonXPath =

            "//button[contains(text(),'Login')]";

 

        driver.findElement(By.xpath(usernameXPath))

                .sendKeys("admin");

 

        driver.findElement(By.xpath(passwordXPath))

                .sendKeys("admin123");

 

        driver.findElement(By.xpath(loginButtonXPath))

                .click();

 

        driver.quit();

    }

}


74. Practical E-Commerce Example

Suppose an e-commerce application displays multiple products:

Laptop

Mobile

Tablet

Headphones

A dynamic XPath can select a product based on its name:

String product = "Laptop";

 

String xpath =

    "//div[contains(@class,'product-card')][.//h2[normalize-space()='"

    + product + "']]";

 

driver.findElement(By.xpath(xpath)).click();

The same code can select another product simply by changing the test data.


75. Practical Dynamic Table Example

String username = "John";

 

String rowXPath =

    "//table//tr[td[normalize-space()='" + username + "']]";

 

String editButtonXPath =

    rowXPath + "//button[contains(text(),'Edit')]";

 

driver.findElement(By.xpath(editButtonXPath)).click();

This approach is useful when a table contains many rows and the required row must be selected based on its data rather than its fixed position.


76. Dynamic XPath with TestNG DataProvider

@DataProvider(name = "users")

public Object[][] users() {

    return new Object[][] {

        {"John"},

        {"David"},

        {"Robert"}

    };

}

 

@Test(dataProvider = "users")

public void userTest(String username) {

 

    String xpath =

        "//div[contains(@class,'user-card')][.//span[normalize-space()='"

        + username + "']]";

 

    driver.findElement(By.xpath(xpath)).click();

}

This demonstrates how Dynamic XPath and Data Providers can work together to test multiple records with one reusable test method.


77. Dynamic XPath with Page Object Model

In a POM-based framework, dynamic XPath should be encapsulated inside page classes.

public class UserPage {

 

    private WebDriver driver;

 

    public UserPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void selectUser(String username) {

 

        String xpath =

            "//div[contains(@class,'user-card')][.//span[normalize-space()='"

            + username + "']]";

 

        driver.findElement(By.xpath(xpath)).click();

    }

}

The test class can then simply call:

userPage.selectUser("John");

This keeps XPath construction and Selenium interaction logic inside the page object.


78. Real-World Dynamic XPath Architecture

Application DOM

      |

      v

Inspect Element

      |

      v

Identify Stable Attribute

      |

      +--------------------+

      |                    |

      v                    v

Stable Text          Stable Attribute

      |                    |

      +---------+----------+

                |

                v

        Dynamic XPath

                |

                v

        Validate in DOM

                |

                v

         Selenium By.xpath()

                |

                v

          WebElement

                |

                v

          Web Interaction

                |

                v

             Assertion


79. Dynamic XPath Learning Roadmap

  1. Understand HTML DOM structure.
  2. Learn basic XPath syntax.
  3. Understand relative XPath.
  4. Learn XPath attributes.
  5. Learn contains().
  6. Learn starts-with().
  7. Learn text().
  8. Learn normalize-space().
  9. Learn XPath axes.
  10. Practice parent-child relationships.
  11. Practice sibling relationships.
  12. Practice dynamic tables.
  13. Practice dynamic product lists.
  14. Combine XPath with Selenium waits.
  15. Use Dynamic XPath with Page Object Model.
  16. Use Dynamic XPath with Data Providers.
  17. Build reusable XPath utility methods.


80. Interview Questions on Dynamic XPath

1. What is Dynamic XPath?

Dynamic XPath is an XPath expression designed to locate elements whose attributes, text, or DOM position may change dynamically.

2. Why is Dynamic XPath used in Selenium?

It helps Selenium locate elements reliably when static attributes such as generated IDs or changing class names are not stable.

3. What is the difference between static and dynamic XPath?

Static XPath generally depends on exact fixed values, while dynamic XPath can use partial values, functions, or DOM relationships to handle changing elements.

4. What is contains() in XPath?

contains() matches an element when a specified substring appears inside an attribute or text value.

5. What is starts-with()?

starts-with() matches an attribute whose value begins with a specified string.

6. Can XPath locate an element using text?

Yes. The text() function can be used to locate elements based on their visible text.

7. What is normalize-space()?

normalize-space() removes leading and trailing whitespace and normalizes sequences of whitespace characters for XPath string comparison.

8. Can Dynamic XPath handle changing IDs?

Yes. Functions such as contains() and starts-with() can identify the stable portion of a dynamic ID.

9. Can Dynamic XPath locate table rows?

Yes. XPath can locate rows using cell values and then navigate to other cells or controls within the row.

10. Can Dynamic XPath be used with Page Object Model?

Yes. Dynamic XPath can be stored and generated inside Page Object classes.

11. Can XPath use multiple conditions?

Yes. XPath supports conditions using operators such as and and or.

12. What is an XPath axis?

An XPath axis describes a relationship between nodes, such as parent, child, ancestor, descendant, following-sibling, and preceding-sibling.

13. How do you locate a button based on partial text?

//button[contains(text(),'Login')]

14. How do you locate an element whose ID starts with a value?

//input[starts-with(@id,'user_')]

15. How do you locate an element relative to another element?

Use XPath relationships such as parent, child, ancestor, descendant, following-sibling, or preceding-sibling.

16. Should indexes always be used in Dynamic XPath?

No. Indexes should be used only when necessary because DOM ordering can change.

17. Can Dynamic XPath be combined with DataProvider?

Yes. DataProvider values can be inserted into XPath expressions to locate different records dynamically.

18. Can Dynamic XPath work with POM?

Yes. POM is a good place to encapsulate reusable dynamic locator logic.

19. Does Dynamic XPath solve synchronization issues?

No. XPath identifies an element, while synchronization should be handled using appropriate waits when the element is not immediately available or interactable.

20. What is the most important rule for Dynamic XPath?

The locator should be based on stable, meaningful information and should uniquely identify the intended element whenever practical.


81. Quick Reference Table

TechniqueExamplePurpose
Exact Attribute//input[@id='username']Stable exact attribute
contains()//input[contains(@id,'user')]Partial attribute match
starts-with()//input[starts-with(@id,'user_')]Dynamic prefix
text()//button[text()='Login']Exact visible text
contains text//button[contains(text(),'Login')]Partial visible text
normalize-space()//button[normalize-space()='Login']Whitespace normalization
Parent//input/parent::divMove to parent
Child//div/child::inputMove to child
Ancestor//input/ancestor::formMove to ancestor
Descendant//div[@id='form']//inputFind nested elements
Following-Sibling//label/following-sibling::inputLocate next sibling
Preceding-Sibling//input/preceding-sibling::labelLocate previous sibling
Index(//button)[2]Select by position
last()//tr[last()]Select last match


82. Practical Exercises

  1. Create a Dynamic XPath for an input whose ID changes on every page load.
  2. Create a Dynamic XPath using contains().
  3. Create a Dynamic XPath using starts-with().
  4. Locate a button using partial text.
  5. Locate an input relative to a label.
  6. Locate a product card using the product name.
  7. Locate a price from a specific product row.
  8. Locate a specific user in a dynamic table.
  9. Click an Edit button inside a selected table row.
  10. Use Dynamic XPath with TestNG DataProvider.
  11. Create a reusable Dynamic XPath method inside a Page Object.
  12. Test XPath expressions using browser developer tools.
  13. Combine Dynamic XPath with explicit waits.
  14. Create a mini Selenium project using dynamic product locators.


83. Summary

Dynamic XPath is an important Selenium skill for locating elements whose attributes, text, or positions change dynamically. Instead of depending entirely on fixed IDs or complete DOM paths, Dynamic XPath allows testers to use stable portions of attributes, partial text, XPath functions, and relationships between elements.

The most commonly used Dynamic XPath techniques include contains(), starts-with(), text(), normalize-space(), parent-child relationships, ancestor-descendant relationships, sibling relationships, and indexed expressions.

Dynamic XPath becomes particularly powerful when combined with Selenium WebDriver, explicit waits, Page Object Model, TestNG Data Providers, and data-driven automation. A well-designed locator should be readable, stable, sufficiently specific, and maintainable.

Final Takeaway: The goal of Dynamic XPath is not to create the most complicated XPath possible. The goal is to create a simple and reliable locator based on stable information in the application's DOM.


84. Course Resources

Learn more about Selenium WebDriver, XPath, TestNG, Page Object Model, data-driven testing, and automation frameworks:

JustAcademy's Selenium course covers Selenium WebDriver, XPath and CSS selectors, dynamic web elements, TestNG, data-driven testing, Page Object Model, framework development, reporting, and practical automation workflows. :contentReference[oaicite:0]{index=0}

whatsapp